﻿using System;
using System.Collections.Generic;
using UnityEngine;
namespace HBFramework
{
    /// <summary>
    /// 状态机
    /// </summary>
    public class StateMechine
    {
        /// <summary>
        /// 当前状态
        /// </summary>
        public IState CurState { get; private set; }
        /// <summary>
        /// 是否正在运行
        /// </summary>
        public bool IsPlaying { get; private set; }
        /// <summary>
        /// 状态列表
        /// </summary>
        private Dictionary<Type, IState> stateDict;

        #region 增减操作

        /// <summary>
        /// 添加状态
        /// </summary>
        /// <param name="state"></param>
        public void AddState(IState state)
        {
            stateDict ??= new Dictionary<Type, IState>();
            var type = state.GetType();
            if (stateDict.ContainsKey(type))
            {
                Debug.LogError($"[StateMechine] id:{type}已存在");
                return;
            }
            state.Master = this;
            stateDict.Add(type, state);
        }

        /// <summary>
        /// 状态转换
        /// </summary>
        /// <param name="state"></param>
        public void TurnToState<T>(params object[] values) where T:IState
        {
            var type = typeof(T);
            if (CurState.GetType() == type)
            {
                Debug.LogError($"[StateMechine] 已处于状态:{type}中");
                return;
            }
            if (!stateDict.ContainsKey(type))
            {
                Debug.LogError($"[StateMechine] 不包含状态:{type}");
                return;
            }
            CurState.OnExit();
            CurState = stateDict[type];
            CurState.OnEnter(values);
        }

        #endregion

        #region 生命周期

        /// <summary>
        /// 运行状态机
        /// </summary>
        /// <param name="state"></param>
        public void Start<T>(params object[] values) where T:IState
        {
            if (IsPlaying)
            {
                Debug.LogError("[StateMechine] 状态机已经在运行中");
                return;
            }
            var type = typeof (T);
            if (!stateDict.ContainsKey(type))
            {
                Debug.LogError($"[StateMechine] 状态{type}不存在");
                return;
            }
            CurState = stateDict[type];
            CurState.OnEnter(values);
            IsPlaying = true;
        }

        /// <summary>
        /// 停止状态机
        /// </summary>
        public void Stop()
        {
            IsPlaying = false;
            CurState.OnExit();
        }

        /// <summary>
        /// 更新状态机
        /// </summary>
        public void Update()
        {
            if (!IsPlaying) return;
            CurState.OnUpdate();
        }

        public void Pause()
        {
            IsPlaying = false;
        }

        public void Continue()
        {
            IsPlaying = true;
        }

        #endregion
    }
}